package com.ccy_blog.back.controller;

import com.ccy_blog.back.bean.Article;
import com.ccy_blog.back.bean.Notice;
import com.ccy_blog.back.bean.User;
import com.ccy_blog.back.service.NoticeService;
import com.ccy_blog.base.bean.ResultVo;
import com.ccy_blog.base.exception.BlogException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    //异步发布公告
    @RequestMapping("/notice/saveOrUpdate")
    @ResponseBody
    public ResultVo saveOrUpdate(Notice notice, HttpSession session){
        ResultVo resultVo = new ResultVo();
        try {
            //获取登录用户
            User user = (User) session.getAttribute("user");
            notice.setUid(user.getUid());
            notice = noticeService.saveOrUpdate(notice);
            resultVo.setOk(true);
            if(notice.getNid() == null){
                resultVo.setMess("发布公告成功");
            }else{
                resultVo.setMess("修改公告成功");
            }
            resultVo.setT(notice);
        }catch (BlogException e){
            resultVo.setMess(e.getMessage());
        }
        return resultVo;
    }

    @RequestMapping("/notice/list")
    @ResponseBody
    public PageInfo<Notice> list(int page, int pageSize, HttpSession session){
        //获取当前登录用户
        User user = (User) session.getAttribute("user");
        //参数1:当前页码 参数2:每页记录数 pageSize 该方法等同于 limit a,b
        PageHelper.startPage(page,pageSize);
        List<Notice> notices = noticeService.list(user.getUid());
        PageInfo<Notice> pageInfo = new PageInfo<>(notices);
        return pageInfo;
    }
    //博客页面公告展示
    @RequestMapping("/notice/allList")
    @ResponseBody
    public List<Notice> allList(HttpServletRequest request, Model model){
        List<Notice> notices = noticeService.list();
        return notices;
    }


    //异步删除公告
    @RequestMapping("/notice/deleteById")
    @ResponseBody
    public ResultVo deleteById(String id){
        ResultVo resultVo = new ResultVo();
        try {
            noticeService.deleteById(id);
            resultVo.setOk(true);
            resultVo.setMess("删除公告成功");
        }catch (BlogException e){
            resultVo.setMess(e.getMessage());
        }
        return resultVo;
    }
}
